package client_commands;

import static client.ClientApplication.clientBinding;

import java.util.StringTokenizer;

import client.ClientApplication;
import client.ClientBindObject;
import client_tree.User;


public class SERV_LOGINCommand extends Command {

	
	public SERV_LOGINCommand(String parameter) {
		setCode(SERV_LOGIN_CMD);
		setParameter(parameter);
	}
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {

		StringTokenizer tokens = new StringTokenizer(getParameter());
		
		String username = tokens.nextToken();
		String nickname = tokens.nextToken();
		String email = tokens.nextToken();
		String ip_address = tokens.nextToken();
		String local_address = tokens.nextToken();
		int port = Integer.parseInt(tokens.nextToken());
		String statusTemp = tokens.nextToken();
		int status = -1;
		
		for (int i = 0; i < STATUS_NAMES.length; i++) {
			if ( statusTemp.equals(STATUS_NAMES[i]) ) {
				status = i;
			}
		}
		
		String regDate = tokens.nextToken();
		String avatar = tokens.nextToken();

		User user = theApp.getClientModel().getOfflineModel().getUserByUsername(username);
		
		if (user == null) {
			return true;
		}
		
		user.setNickname(nickname);
		user.setEmail(email);
		user.setIp_address(ip_address);
		user.setLocalAddress(local_address);
		user.setPort(port);
		user.setStatus(status);
		user.setRegDate(regDate);
		user.setAvatar(avatar);
		
		theApp.getClientModel().addUser(user);
		
		
		ClientBindObject cbo = clientBinding.get(username);
		
		if ( cbo != null && cbo.getDialog() != null ) {
			cbo.getDialog().setSendButtonRights(true);
			theApp.getWindow().getActionManager().getAudioCallAction().setEnabled(true);
			theApp.getWindow().getActionManager().getVideoCallAction().setEnabled(true);
			theApp.getWindow().getActionManager().getStopCallAction().setEnabled(true);
			cbo.getDialog().startTypingListener();
		}
		
		return true;
	}
	
}
